package com.zlm.user.partner.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zlm.common.base.AbstractBaseService;
import com.zlm.common.base.PageEntity;
import com.zlm.common.constants.CodeConstants;
import com.zlm.common.constants.CommonConstants;
import com.zlm.common.constants.NumberConstants;
import com.zlm.common.dto.HxGroupDto;
import com.zlm.common.dto.userPartner.SysPartnerDto;
import com.zlm.common.entity.UserGroupDO;
import com.zlm.common.entity.UserGroupRelationDO;
import com.zlm.huanxin.util.HuanxinUtils;
import com.zlm.user.partner.dao.SysPartnerDao;
import com.zlm.user.partner.dao.UserGroupDao;
import com.zlm.user.partner.dao.UserGroupRelationDao;
import com.zlm.user.partner.service.UserGroupService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: duyufu
 * @Date: 2019/7/17 16:44
 */
@Service
public class UserGroupServiceImpl extends AbstractBaseService<UserGroupDao, UserGroupDO> implements UserGroupService {

    @Autowired
    @Override
    public void setBaseDao(UserGroupDao userGroupDao) {
        this.baseDao = userGroupDao;
    }

    @Autowired
    private SysPartnerDao sysPartnerDao;

    @Autowired
    private UserGroupRelationDao userGroupRelationDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addGroup(HxGroupDto groupDto) {
        Map<String,Object> map = new HashMap<>(8);
        map.put("groupname",groupDto.getGroupName());
        map.put("desc",groupDto.getDescription());
        map.put("public",groupDto.getIsPublic());
        map.put("owner",groupDto.getOwner());
        if (null != groupDto.getMaxUsers()) {
            map.put("maxusers",groupDto.getMaxUsers());
        }
        if (null != groupDto.getMembersOnly()) {
            map.put("members_only",groupDto.getMembersOnly());
        }
        if (null != groupDto.getAllowInvites()) {
            map.put("allowinvites",groupDto.getAllowInvites());
        }
        if (null != groupDto.getMembers()) {
            map.put("members",groupDto.getMembers());
        }
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(map));
        Map<String, Object> result = HuanxinUtils.createGroup(json);
        String groupHxId = (String) result.get("groupid");
        UserGroupDO group = new UserGroupDO();
        group.setGroupName(groupDto.getGroupName());
        group.setDescription(groupDto.getDescription());
        group.setGroupHxId(groupHxId);
        group.setCreateUser(groupDto.getOwner());
        group.setLastModifyUser(groupDto.getOwner());
        baseDao.addGroup(group);
        UserGroupRelationDO relationDO = new UserGroupRelationDO();
        relationDO.setUserHxId(groupDto.getOwner());
        relationDO.setGroupHxId(groupHxId);
        relationDO.setUserType(NumberConstants.NUM_2);
        userGroupRelationDao.editHxGroupAdmin(relationDO);
        return groupHxId;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addHxGroupMember(String groupHxId, List<String> userHxIds) {
        //获取已在群组中的成员
        List<String> members = userGroupRelationDao.queryMemberIdByHxId(groupHxId);
        //清除掉已存在群组的成员
        userHxIds.removeAll(members);
        Map<String,Object> map = new HashMap<>(1);
//        Object[] objects = userHxIds.toArray();
//        System.out.println(objects);
        map.put("usernames",userHxIds);
//        map.put("usernames",objects);
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(map));
        userGroupRelationDao.addHxGroupMember(groupHxId,userHxIds);
        HuanxinUtils.addHxGroupMember(groupHxId, json);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteHxGroupMember(String groupHxId, List<String> userHxIds) {
        StringBuilder sb = new StringBuilder();
        for (String userHxId : userHxIds) {
            sb.append(userHxId).append(",");
        }
        String s = sb.toString();
        userGroupRelationDao.deleteHxGroupMember(groupHxId,userHxIds);
        HuanxinUtils.deleteHxGroupMember(groupHxId,s.substring(0,s.length()-1));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteHxGroup(Integer userId, String groupHxId) {
        SysPartnerDto sysPartnerDto = sysPartnerDao.queryPartnerById(userId);
        String hxId = sysPartnerDto.getHxId();
        UserGroupDO group = baseDao.queryGroupByHxId(groupHxId);
        if (StringUtils.isBlank(hxId) || !group.getCreateUser().equals(hxId)) {
            throw new RuntimeException(CodeConstants.CODE_10022);
        }
        userGroupRelationDao.deleteUserGroupRelation(groupHxId);
        baseDao.deleteUserGroupByHxId(groupHxId);
        HuanxinUtils.deleteHxGroup(groupHxId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteSingleHxGroupMember(String groupHxId, String userHxId) {
        userGroupRelationDao.deleteSingleHxGroupMember(groupHxId,userHxId);
        HuanxinUtils.deleteSingleHxGroupMember(groupHxId,userHxId);
    }

    @Override
    public PageEntity getHxGroupMember(String groupHxId, Integer pagenum, Integer pagesize) {
        int count = userGroupRelationDao.countMemberByHxId(groupHxId);
        if (null == pagesize || pagesize >= CommonConstants.maxPageSize) {
            pagesize = CommonConstants.pageSize;
        }
        if (null == pagenum || pagenum.intValue() == NumberConstants.NUM_0) {
            pagenum = CommonConstants.pageNumber;
        }else {
            pagenum = (pagenum-1) * pagesize;
        }
        List<UserGroupRelationDO> memberList = userGroupRelationDao.getHxGroupMember(groupHxId,pagenum,pagesize);
        PageEntity page = getPage(pagenum,pagesize,count,memberList);
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateHxGroup(Integer userId, String groupHxId, String groupname, String description, Integer maxusers) {
        SysPartnerDto sysPartnerDto = sysPartnerDao.queryPartnerById(userId);
        String hxId = sysPartnerDto.getHxId();
        UserGroupDO group = baseDao.queryGroupByHxId(groupHxId);
        if (StringUtils.isBlank(hxId) || !group.getCreateUser().equals(hxId)) {
            throw new RuntimeException(CodeConstants.CODE_10022);
        }
        baseDao.updateHxGroup(groupHxId,groupname,description);
        HuanxinUtils.updateHxGroup(groupHxId,groupname,description,maxusers);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addHxGroupAdmin(Integer userId, String groupHxId, String userHxId) {
        checkHxGroupParams(userId, groupHxId);
        UserGroupRelationDO relation = new UserGroupRelationDO();
        relation.setGroupHxId(groupHxId);
        relation.setUserHxId(userHxId);
        relation.setUserType(NumberConstants.NUM_1);
        userGroupRelationDao.editHxGroupAdmin(relation);
        HuanxinUtils.addHxGroupAdmin(groupHxId,userHxId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteHxGroupAdmin(Integer userId, String groupHxId, String userHxId) {
        checkHxGroupParams(userId, groupHxId);
        UserGroupRelationDO relation = new UserGroupRelationDO();
        relation.setGroupHxId(groupHxId);
        relation.setUserHxId(userHxId);
        relation.setUserType(NumberConstants.NUM_0);
        userGroupRelationDao.editHxGroupAdmin(relation);
        HuanxinUtils.deleteHxGroupAdmin(groupHxId,userHxId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void transferHxGroup(Integer userId, String groupHxId, String userHxId) {
        String hxId = checkHxGroupParams(userId, groupHxId);
        UserGroupRelationDO relationDO = new UserGroupRelationDO();
        relationDO.setGroupHxId(groupHxId);
        relationDO.setUserHxId(hxId);
        relationDO.setUserType(NumberConstants.NUM_0);
        userGroupRelationDao.editHxGroupAdmin(relationDO);
        UserGroupRelationDO relation = new UserGroupRelationDO();
        relation.setGroupHxId(groupHxId);
        relation.setUserHxId(userHxId);
        relation.setUserType(NumberConstants.NUM_2);
        userGroupRelationDao.editHxGroupAdmin(relation);
        HuanxinUtils.transferHxGroup(groupHxId,userHxId);
    }

    @Override
    public List<Map<String, Object>> getHxGroupAdmin(String groupHxId) {
        List<Map<String,Object>> adminList = userGroupRelationDao.getHxGroupAdmin(groupHxId);
        return adminList;
    }

    @Override
    public List<UserGroupDO> getAllJoinedGroup(Integer userId) {
        SysPartnerDto sysPartnerDto = sysPartnerDao.queryPartnerById(userId);
        String hxId = sysPartnerDto.getHxId();
        List<UserGroupDO> adminList =  baseDao.getAllJoinedGroup(hxId);
        return adminList;
    }

    @Override
    public UserGroupDO getGroupDetail(String groupHxId) {
        return baseDao.queryGroupByHxId(groupHxId);
    }

    private String checkHxGroupParams(Integer userId, String groupHxId) {
        SysPartnerDto sysPartnerDto = sysPartnerDao.queryPartnerById(userId);
        String hxId = sysPartnerDto.getHxId();
        //判断群主身份
        Integer userType = NumberConstants.NUM_2;
        UserGroupRelationDO userGroupRelationDO = userGroupRelationDao.queryMemberByHxId(groupHxId, hxId,userType);
        if (null == userGroupRelationDO) {
            throw new RuntimeException(CodeConstants.CODE_FAIL);
        }
        return hxId;
    }


}
